//
//  UIImageView+SDWebCache.m
//  SDWebData
//
//  Created by stm on 11-7-13.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SDImageView+SDWebCache.h"
#import "CustomObject.h"
@implementation UIImageView(SDWebCacheCategory)

- (void)setImageWithURL:(NSURL *)url block:(imageCallback)block
{
    [self setImageWithURL:url refreshCache:NO block:block];
}

- (void)setImageWithURL:(NSURL *)url refreshCache:(BOOL)refreshCache block:(imageCallback)block
{
	[self setImageWithURL:url refreshCache:refreshCache placeholderImage:nil  block:block];
}

- (void)setImageWithURL:(NSURL *)url refreshCache:(BOOL)refreshCache placeholderImage:(UIImage *)placeholder block:(imageCallback)block
{
	
    // Remove in progress downloader from queue
	
    self.image = placeholder;
	
    if (url)
    {
        if ([[CustomObject sharedCustomObject] isExistImage:url]) {
            self.image = [[CustomObject sharedCustomObject]getImage:url];
            if (block) {
                block(self,self.image);
            }
        }
        else{
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData * data = [[NSData alloc]initWithContentsOfURL:url];
                UIImage *image = [[UIImage alloc]initWithData:data];
                if (data != nil) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if (block) {
                            block(self,image);
                        }
                        [[CustomObject sharedCustomObject] addImage:image key:url];
                        self.image = image;

                    });
                }
            });
        }
    }
}

@end
